//
//  DetailsCollectionViewCell.m
//  TodatPlay
//
//  Created by dllo on 16/9/6.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "DetailsCollectionViewCell.h"
//Tool
#import "SDAutoLayout.h"
#import "TAMacro.h"
#import "DetailsHeadView.h"
#import "CDMNetTool.h"
#import "UIImageView+WebCache.h"
#import "UIImage+ImageScale.h"
// cell
#import "WebViewTableViewCell.h"
#import "HighlightsTableViewCell.h"
#import "InterestedTableViewCell.h"
#import "NormalTableViewCell.h"
#import "ByeNowTableViewCell.h"
#import "PromptTableViewCell.h"
#import "RecommendTableViewCell.h"
// model
#import "DetailsData.h"
#import "DetailsProjinfo.h"
#import "WebViewObj.h"
#import "WebViewRootClass.h"
#import "RecommendModel.h"

// 宏
#define kTableViewCellNormalReuse @"normalReuse"
#define kTableViewCellByeNowReuse @"ByeNowReuse"
#define kTableViewCellRecommendReuse @"recommendReuse"
#define kTableViewCellProptResue @"proptReuse"
#define kTableViewCellWebViewReuse @"WebViewReuse"
#define kTableViewCellHighlightReuse @"highlightReuse"
#define kTableViewCellInterestedResue @"interestedReuse"
@interface DetailsCollectionViewCell ()<UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate>
@property (nonatomic, strong) UITableView *detailesTableView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) WebViewRootClass *webViewRootData;
@property (nonatomic, strong) NSMutableArray<RecommendModel *> *recommendArr;
@end

@implementation DetailsCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createTableView];
        self.recommendArr = [NSMutableArray array];
        
    }
    return self;
}
- (void)setData:(DetailsData *)data {
    _data = data;
//    NSLog(@"%@", _data);
    [self.detailesTableView reloadData];
    [self handleData];
    
}
- (void)setProjinfo:(DetailsProjinfo *)projinfo {
    _projinfo = projinfo;
    
    [self.detailesTableView reloadData];
    [self handleRecommendData];
}
- (void)createTableView {
    self.detailesTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    [self.contentView addSubview:_detailesTableView];
    self.detailesTableView.delegate = self;
    self.detailesTableView.dataSource = self;
    [self.detailesTableView registerClass:[NormalTableViewCell class] forCellReuseIdentifier:kTableViewCellNormalReuse];
    [self.detailesTableView registerClass:[ByeNowTableViewCell class] forCellReuseIdentifier:kTableViewCellByeNowReuse];
     [self.detailesTableView registerClass:[PromptTableViewCell class] forCellReuseIdentifier:kTableViewCellProptResue];
    [self.detailesTableView registerNib:[UINib nibWithNibName:@"RecommendTableViewCell" bundle:nil] forCellReuseIdentifier:kTableViewCellRecommendReuse];
    [self.detailesTableView registerClass:[WebViewTableViewCell class] forCellReuseIdentifier:kTableViewCellWebViewReuse];
    [self.detailesTableView registerClass:[HighlightsTableViewCell class] forCellReuseIdentifier:kTableViewCellHighlightReuse];
    [self.detailesTableView registerClass:[InterestedTableViewCell class] forCellReuseIdentifier:kTableViewCellInterestedResue];

}
#pragma mark - 处理数据
- (void)handleRecommendData {
    NSString *HTTPStr = @"http://apprecommend.damai.cn/wireless-recommend/wan/projectdetailpage?platform=4&visitorId=V4sA1MPjN70DAAg7G0LY5WTo&source=10345&version=203004&useCash=false&ip=172.16.2.192&channel_from=m360_market&cityId=110000";
    NSString *geoString = self.projinfo.geo;

    NSArray *geoArr = [geoString componentsSeparatedByString:@","];
    NSString *lonString = geoArr.lastObject;
    NSString *latString = geoArr.firstObject;
    NSString *projectID = [NSString stringWithFormat:@"%ld", self.projinfo._id];
    
    if (projectID.length > 2) {
        NSString *finalURLString = [[[HTTPStr stringByAppendingFormat:@"&projectId=%@", projectID] stringByAppendingFormat:@"&lon=%@", lonString]stringByAppendingFormat:@"&lat=%@", latString];
        

    [CDMNetTool GET:finalURLString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
//        NSLog(@"请求成功:%@", result);
        for (NSDictionary *dic in result) {
            RecommendModel *model = [RecommendModel new];
            [model setValuesForKeysWithDictionary:dic];
            [_recommendArr addObject:model];
        }
        [self.detailesTableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败:%@", error);
    }];
    }
    
}
- (void)handleData {
    
    NSString *str = @"http://fb.jtwsm.cn/client/GetProjectDesc_V1.do?platform=4&channel_from=m360_market&source=10345&version=203004&useCash=false";
    NSString *activityIdStr = [NSString stringWithFormat:@"activityId=%@", self.data.projinfo.realid];
    NSString *finalString = [str stringByAppendingFormat:@"&%@", activityIdStr];
//    NSLog(@"%@", activityIdStr);
    [CDMNetTool GET:finalString andBody:nil andHeader:nil andResponse:CDMJSON andSuccessBlock:^(id result) {
        self.webViewRootData = [WebViewRootClass modelWithDic:result];
//        NSLog(@"请求成功:%@", result);
        [self createWebView];
        [self.detailesTableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败:%@", error);
    }];
    }
- (void)createWebView {
    
    _webView = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    _webView.backgroundColor = [UIColor cyanColor];
    _webView.delegate = self;
    _webView.scrollView.bounces = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
    [_webView sizeToFit];
    
    //设置内容，这里包装一层div，用来获取内容实际高度（像素），htmlcontent是html格式的字符串//
    NSString *urlString = self.webViewRootData.obj.projectDesc;
//    NSLog(@"%@", urlString);
    NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", urlString];
    [_webView loadHTMLString:htmlcontent baseURL:nil];
    [self.detailesTableView reloadData];
}
#pragma mark - datasource and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 6;
    } else if (section == 1){
        return 1;
    } else if (section == 2){
        return 1;
    } else if (section == 3){
        return 1;
    } else {
        return 4;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            HighlightsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellHighlightReuse];
            cell.highlightsLabel.text = self.data.projinfo.highlights;
            return cell;
        } else if (indexPath.row == 1) {
            NormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellNormalReuse];
            cell.textString = self.projinfo.timestr;
            return cell;
        } else if (indexPath.row == 2) {
            NormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellNormalReuse];
            cell.textString = self.projinfo.address;
            return cell;
        } else if (indexPath.row == 3) {
            NormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellNormalReuse];
            cell.textString = self.projinfo.orgname;
            return cell;
        } else if (indexPath.row == 4) {
            NormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellNormalReuse];
            cell.textString = @"加入讨论组聊聊吧";
            return cell;
        } else {
            InterestedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellInterestedResue];
            cell.numberOfInteresting = [NSString stringWithFormat:@"%ld", self.data.projinfo.likercount];
            return cell;
        }
    
    } else if(indexPath.section == 1){
        WebViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellWebViewReuse];
        cell.webURLString = self.webViewRootData.obj.projectDesc;
        
        return cell;
    } else if (indexPath.section == 2){
        ByeNowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellByeNowReuse];
        cell.is_wifi.text = [NSString stringWithFormat:@"%@", self.data.projinfo.is_wifi];
        cell.is_reserve.text = [NSString stringWithFormat:@"%@", self.data.projinfo.is_reserve];
        cell.is_parking_space.text = [NSString stringWithFormat:@"%@", self.data.projinfo.is_parking_space];
        cell.age_limit.text = [NSString stringWithFormat:@"年龄限制: %@", self.data.projinfo.age_limit];
        cell.for_tickets_desc.text =  [NSString stringWithFormat:@"%@", self.data.projinfo.for_tickets_desc];
        cell.support_hotline.text = [NSString stringWithFormat:@"咨询电话: %@", self.data.projinfo.support_hotline];
        
        return cell;
    }else if (indexPath.section == 3) {
        PromptTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellProptResue];
        if (self.data.projinfo.tips.length == 0) {
            cell.summaryLabel.text = @"暂时没有提示";
        } else {
        cell.summaryLabel.text = self.data.projinfo.tips;
        }
        return cell;
        
    } else {
        RecommendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellRecommendReuse];
        
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:_recommendArr[indexPath.row].pic]  placeholderImage:[UIImage imageNamed:@"project_bg_detail"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            // 将image转换成data类型
//            NSData *imageData = UIImagePNGRepresentation(image);

            
            
        }];
        cell.titleLabel.text = _recommendArr[indexPath.row].title;
        cell.endTimeLabel.text = _recommendArr[indexPath.row].timestr;
        cell.addressLabel.text = _recommendArr[indexPath.row].address;
        return cell;
    }
}

#pragma mark -返回cell的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return [self cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:self.detailesTableView];
    } else if (indexPath.section == 1) {
        return _webView.frame.size.height;
    } else if (indexPath.section == 2) {
        return [self cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:self.detailesTableView];
    } else if (indexPath.section == 3){
        return [self cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:self.detailesTableView];
    } else {
        return 100;
    };
}
#pragma mark - 返回头视图和它的高
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        DetailsHeadView *headView = [[DetailsHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
        [headView.picImageView sd_setImageWithURL:[NSURL URLWithString:self.data.projinfo.pic] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        }];
        headView.titleLabel.text = self.data.projinfo.title;
        headView.pricestrLabel.text = self.data.projinfo.pricestr;
        headView.backgroundColor = [UIColor whiteColor];

        return headView;
    } else if (section == 1){
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, -10, SCREEN_WIDTH , 40)];
        [backView addSubview:label];
        label.text = @"活动详情";
        return backView;
    } else if (section == 2) {
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, -10, SCREEN_WIDTH , 40)];
        [backView addSubview:label];
        label.text = @"购买须知";
        return backView;

    } else if (section == 3){
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, -10, SCREEN_WIDTH , 40)];
        [backView addSubview:label];
        label.text = @"温馨提示";
        return backView;
    } else {
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, -10, SCREEN_WIDTH , 40)];
        [backView addSubview:label];
        label.text = @"相关推荐";
        return backView;
    }
}
#pragma mark - 返回头视图的高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 315;
    } else {
        
        return 30;
    }
}

#pragma mark - UIWebView Delegate Methods
-(void)webViewDidFinishLoad:(UIWebView *)webView
{    //获取页面高度（像素）
    NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    float clientheight = [clientheight_str floatValue];
    //设置到WebView上
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, clientheight);
    //获取WebView最佳尺寸（点）
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    //获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    float height = [height_str floatValue];
    //内容实际高度（像素）* 点和像素的比
    height = height * frame.height / clientheight;
    //再次设置WebView高度（点）
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
    [self.detailesTableView reloadData];
    
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    NSLog(@"webViewDidStartLoad");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
//    NSLog(@"didFailLoadWithError===%@", error);
}

@end
